import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/Home/index.vue'),
      meta: {
        requireAuth: false
      }
    },
    {
      path:'/:pathMatch(.*)',
      redirect: '/404',
      children:[
        {
          path: '/404',
          name: '404',
          component: () => import ('../views/Error/404.vue'),
        }
      ]
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: () => import('@/views/Detail/index.vue'),
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('@/views/About/index.vue'),
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/goods',
      name: 'goods',
      component: () => import('@/views/Goods/index.vue'),
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/user',
      name: 'user',
      component: () => import('@/views/User/index.vue'),
      meta: {
        requireAuth: true
      },
      redirect: '/user/info',
      children: [
        {
          path: 'info',
          name: 'info',
          component: () => import('@/views/User/Info/index.vue'),
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'list',
          name: 'lendingList',
          component: () => import('@/views/User/List/index.vue'),
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'collect',
          name: 'collect',
          component: () => import('@/views/User/Collect/index.vue'),
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'record',
          name: 'record',
          component: () => import('@/views/User/Record/index.vue'),
          meta: {
            requireAuth: true
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth && !sessionStorage.getItem('token')){
    next('/')
    ElMessage.error('请先登录')
  }else{
    next()
  }
})

export default router
